<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="轮播图片" prop="url">
<!--        <el-input v-model="dataForm.url" placeholder="轮播图片"></el-input>-->
        <el-upload
          class="upload-demo"
          action="#"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :http-request="uploadImg"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <img width="100px" height="100px" v-if="dataForm.url" :src="'http://localhost:8080/renren-fast' + dataForm.url"/>
          <br v-if="dataForm.url">
          <el-button size="small" type="primary">点击上传</el-button>
          <!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      type: 'banner',
      visible: false,
      fileList: [],
      dataForm: {
        id: 0,
        url: ''
      },
      dataRule: {
        url: [
          { required: true, message: '轮播图片不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.fileList = [];
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/manage/banner/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.url = data.banner.url
              const parts = data.banner.url.split('/')
              this.fileList.push({
                name: parts[parts.length - 1],
                url: 'http://localhost:8080/renren-fast' + data.banner.url
              })
            }
          })
        }
      })
    },
    uploadImg (item) {
      const fileObj = item.file
      console.log(fileObj.name)
      // FormData 对象
      const form01 = new FormData()
      // 文件对象
      form01.append('file', fileObj)
      this.$http({
        url: this.$http.adornUrl(`/manage/file/upload/${this.type}`),
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: form01
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 0) {
          this.$message({
            message: '上传成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.fileList.push({
                name: fileObj.name,
                url: 'http://localhost:8080/renren-fast' + data.fileInfo
              })
              this.dataForm.url = data.fileInfo
            }
          })
        } else {
          this.$message({
            message: '上传失败',
            type: 'warning',
            duration: 1500,
            onClose: () => {
            }
          })
        }
      }).catch(() => {
        this.$message.error('异常错误')
      })
    },
    handleRemove (item, fileList) {
      console.log(item, fileList)
      var filename = item.name
      console.log('删除文件名：', filename)
      this.$http({
        url: this.$http.adornUrl(`/manage/file/delete/${this.type}`),
        method: 'post',
        data: this.$http.adornData({
          'filename': filename
        })
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 0) {
          this.$message({
            message: '移除成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.fileList = this.fileList.filter(item => item.name !== filename)
              this.dataForm.url = ''
            }
          })
        } else {
          this.$message({
            message: '移除失败',
            type: 'warning',
            duration: 1500,
            onClose: () => {
            }
          })
        }
      }).catch(() => {
        this.$message.error('异常错误')
      })
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 表单提交
    dataFormSubmit () {
      console.log(this.dataForm)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/manage/banner/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'url': this.dataForm.url
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
